﻿
using CSRedis;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Htx.Redis.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HomeController : ControllerBase
    {

        private readonly ILogger<HomeController> _logger;
        private readonly IConfiguration _configuration;

        public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        /// <summary>
        /// 获取应用标题
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Index()
        {
            return "CSRedisCore和Redis哨兵";
        }

        /// <summary>
        /// 设置键值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="val"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Obj1> Set([FromQuery] string key, [FromQuery] string val)
        {
            RedisHelper.Set(key, JsonConvert.SerializeObject(new Obj1 { Id = await RedisHelper.IncrByAsync("sys_num"), Name = val }));
            var obj = JsonConvert.DeserializeObject<Obj1>(RedisHelper.Get(key));

            return obj;

        }

        [HttpGet("setnx")]
        public async Task<bool> Setnx([FromQuery] string val, [FromServices] CSRedisClient client)
        {
            var ret = await client.SetAsync("huatianxiao", val, 10, RedisExistence.Nx);
            return ret;
        }

    }

    public class Obj1
    {
        public long Id { get; set; }
        public string Name { get; set; }
    }


}
